package wifiunion.com.notice.utils.imageprocess.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


import java.io.File;
import java.util.ArrayList;

import wifiunion.com.notice.R;
import wifiunion.com.notice.utils.imageprocess.fragment.ImageSelectorFragment;
import wifiunion.com.notice.utils.imageprocess.utils.FileUtils;
import wifiunion.com.notice.utils.imageprocess.utils.ImageConfig;
import wifiunion.com.notice.utils.imageprocess.utils.ImageSelector;
import wifiunion.com.notice.utils.imageprocess.utils.Utils;

/**
 *
 * @ClassName ImageSelectorActivity
 * @Description 图片选择器
 * @Version
 * @Author wifiunion
 * @Creation 2016年6月20日 下午3:56:07
 * @Mender wifiunion
 * @Modification 2016年6月20日 下午3:56:07
 *
 */
public class ImageSelectorActivity extends FragmentActivity implements ImageSelectorFragment.Callback {

	public static final String EXTRA_RESULT = "select_result";

	private ArrayList<String> pathList = new ArrayList<String>();

	/**
	 * 初始的图片列表，场景：选择了很多图片后，点击返回按钮，或者back键的时候，返回这个列表
	 */
	private ArrayList<String> originPathList = new ArrayList<String>();

	private ImageConfig imageConfig;

	private TextView title_text;
	private TextView submitButton;
	// private RelativeLayout imageselector_title_bar_layout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.imageselector_activity);

		imageConfig = ImageSelector.getImageConfig();

		if(null != imageConfig)
		{

			if (imageConfig.isOpenCamera()) {
				showCameraAction();
			} else {
				originPathList.addAll(imageConfig.getPathList());
				// Utils.hideTitleBar(this, R.id.imageselector_activity_layout,
				// imageConfig.getSteepToolBarColor());

				getSupportFragmentManager().beginTransaction()
						.add(R.id.image_grid, Fragment.instantiate(this, ImageSelectorFragment.class.getName(), null))
						.commit();

				submitButton = (TextView) super.findViewById(R.id.title_right);
				title_text = (TextView) super.findViewById(R.id.title_text);
				// imageselector_title_bar_layout = (RelativeLayout)
				// super.findViewById(R.id.imageselector_title_bar_layout);

				init();
			}
		}
		else
		{
			finish();
		}

	}

	private void init() {

		submitButton.setTextColor(imageConfig.getTitleSubmitTextColor());
		title_text.setTextColor(imageConfig.getTitleTextColor());
		// imageselector_title_bar_layout.setBackgroundColor(imageConfig.getTitleBgColor());

		pathList = imageConfig.getPathList();

		if (pathList.contains("-1")) {
			pathList.remove("-1");
		}
		findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent data = new Intent();
				data.putStringArrayListExtra(EXTRA_RESULT, originPathList);
				setResult(RESULT_OK, data);
				exit();
			}
		});

		if (pathList == null || pathList.size() <= 0) {
			submitButton.setText(R.string.finish);
			submitButton.setTextColor(imageConfig.getTitleSubmitTextColor());
			submitButton.setBackgroundColor(getResources().getColor(R.color.headbgcolor));
			submitButton.setEnabled(false);
		} else {
			submitButton.setText((getResources().getText(R.string.finish)) + "(" + pathList.size() + "/"
					+ imageConfig.getMaxSize() + ")");
			submitButton.setBackgroundResource(R.drawable.button_bg_selector);
			submitButton.setTextColor(getResources().getColor(R.color.white));
			submitButton.setEnabled(true);
		}
		submitButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (pathList != null && pathList.size() > 0) {
					Intent data = new Intent();
					data.putStringArrayListExtra(EXTRA_RESULT, pathList);
					setResult(RESULT_OK, data);
					exit();
				}
			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == ImageSelector.IMAGE_CROP_CODE) {
			if (resultCode == RESULT_OK) {
				Intent intent = new Intent();
				// 这边判断下是否为单选，单选则清空列表
				if (!imageConfig.isMutiSelect()) {
					pathList.clear();
				}
				pathList.add(cropImagePath);
				intent.putStringArrayListExtra(EXTRA_RESULT, pathList);
				setResult(RESULT_OK, intent);
				exit();
			} else {
				exit();
			}
		} else if (requestCode == REQUEST_CAMERA) {
			if (resultCode == Activity.RESULT_OK) {
				if (tempFile != null) {
					if (imageConfig.isCrop()) {

						if(imageConfig.isCropRule())
						{
							crop(tempFile.getAbsolutePath()/*, imageConfig.getAspectX(), imageConfig.getAspectY(),
								imageConfig.getOutputX(), imageConfig.getOutputY()*/);
						}
						else
						{
							crop(tempFile.getAbsolutePath(), imageConfig.getAspectX(), imageConfig.getAspectY(),
								imageConfig.getOutputX(), imageConfig.getOutputY());
						}


					} else {
						Intent cameraintent = new Intent();
						pathList.add(tempFile.getAbsolutePath());
						cameraintent.putStringArrayListExtra(EXTRA_RESULT, pathList);
						setResult(RESULT_OK, cameraintent);
						exit();
					}
				}
			} else {
				if (tempFile != null && tempFile.exists()) {
					tempFile.delete();
				}
				finish();
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private void exit() {
		finish();
	}

	private String cropImagePath;

	private void crop(String imagePath, int aspectX, int aspectY, int outputX, int outputY) {
		File file;
		if (Utils.existSDCard()) {
			file = new File(Environment.getExternalStorageDirectory() + imageConfig.getFilePath(),
					Utils.getImageName());
		} else {
			file = new File(getCacheDir(), Utils.getImageName());
		}

		cropImagePath = file.getAbsolutePath();
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(Uri.fromFile(new File(imagePath)), "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", aspectX);
		intent.putExtra("aspectY", aspectY);
//		intent.putExtra("outputX", outputX);
//		intent.putExtra("outputY", outputY);
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		startActivityForResult(intent, ImageSelector.IMAGE_CROP_CODE);
	}

	private void crop(String imagePath) {
		File file;
		if (Utils.existSDCard()) {
			file = new File(Environment.getExternalStorageDirectory() + imageConfig.getFilePath(),
					Utils.getImageName());
		} else {
			file = new File(getCacheDir(), Utils.getImageName());
		}

		cropImagePath = file.getAbsolutePath();
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(Uri.fromFile(new File(imagePath)), "image/*");
		intent.putExtra("crop", "true");
		if(Build.BRAND.equals("HUAWEI"))
		{
			intent.putExtra("aspectX", 9999);
			intent.putExtra("aspectY", 9998);
		}
		else
		{
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
		}

		intent.putExtra("scale", true);
		intent.putExtra("circleCrop", false);
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		startActivityForResult(intent, ImageSelector.IMAGE_CROP_CODE);
	}

	@Override
	public void onSingleImageSelected(String path) {
		if (imageConfig.isCrop()) {
			if(imageConfig.isCropRule())
			{
				crop(path/*, imageConfig.getAspectX(), imageConfig.getAspectY(), imageConfig.getOutputX(),
					imageConfig.getOutputY()*/);
			}
			else
			{
				crop(path, imageConfig.getAspectX(), imageConfig.getAspectY(), imageConfig.getOutputX(),
					imageConfig.getOutputY());
			}


		} else {
			Intent data = new Intent();
			pathList.clear();
			pathList.add(path);
			data.putStringArrayListExtra(EXTRA_RESULT, pathList);
			setResult(RESULT_OK, data);
			exit();
		}
	}

	@Override
	public void onImageSelected(String path) {
		if (!pathList.contains(path)) {
			pathList.add(path);
		}

		if (pathList.contains("-1")) {
			pathList.remove("-1");
		}
		if (pathList.size() > 0) {
			submitButton.setText((getResources().getText(R.string.finish)) + "(" + pathList.size() + "/"
					+ imageConfig.getMaxSize() + ")");
			if (!submitButton.isEnabled()) {
				// submitButton.setBackgroundColor(getResources().getColor(R.color.backgroud_color));
				submitButton.setBackgroundResource(R.drawable.button_bg_selector);
				submitButton.setTextColor(getResources().getColor(R.color.white));
				submitButton.setEnabled(true);
			}
		}
	}

	@Override
	public void onImageUnselected(String path) {

		if (pathList.contains("-1")) {
			pathList.remove("-1");
		}
		if (pathList.contains(path)) {
			pathList.remove(path);
			submitButton.setText((getResources().getText(R.string.finish)) + "(" + pathList.size() + "/"
					+ imageConfig.getMaxSize() + ")");
			// submitButton.setBackgroundColor(getResources().getColor(R.color.backgroud_color));
			submitButton.setBackgroundResource(R.drawable.button_bg_selector);
			submitButton.setTextColor(getResources().getColor(R.color.white));
		} else {
			// submitButton.setBackgroundColor(getResources().getColor(R.color.backgroud_color));
			submitButton.setBackgroundResource(R.drawable.button_bg_selector);
			submitButton.setTextColor(getResources().getColor(R.color.white));
			submitButton.setText((getResources().getText(R.string.finish)) + "(" + pathList.size() + "/"
					+ imageConfig.getMaxSize() + ")");
		}
		if (pathList.size() == 0) {
			submitButton.setText(R.string.finish);
			submitButton.setTextColor(imageConfig.getTitleSubmitTextColor());
			submitButton.setBackgroundColor(getResources().getColor(R.color.headbgcolor));
			submitButton.setEnabled(false);
		}
	}

	@Override
	public void onCameraShot(File imageFile) {
		// if (imageFile != null) {
		// Intent data = new Intent();
		// pathList.add(imageFile.getAbsolutePath());
		// data.putStringArrayListExtra(EXTRA_RESULT, pathList);
		// setResult(RESULT_OK, data);
		// exit();
		// }
		if (imageFile != null) {
			if (imageConfig.isCrop()) {
				crop(imageFile.getAbsolutePath()/*, imageConfig.getAspectX(), imageConfig.getAspectY(),
						imageConfig.getOutputX(), imageConfig.getOutputY()*/);
			} else {
				Intent data = new Intent();
				pathList.add(imageFile.getAbsolutePath());
				data.putStringArrayListExtra(EXTRA_RESULT, pathList);
				setResult(RESULT_OK, data);
				exit();
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				Intent data = new Intent();
				data.putStringArrayListExtra(EXTRA_RESULT, originPathList);
				setResult(RESULT_OK, data);
				exit();
				break;
		}
		return super.onKeyDown(keyCode, event);
	}

	private File tempFile;

	private static final int REQUEST_CAMERA = 100;

	/**
	 * 选择相机
	 */
	private void showCameraAction() {
		// 跳转到系统照相机
		Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		if (cameraIntent.resolveActivity(this.getPackageManager()) != null) {
			// 设置系统相机拍照后的输出路径
			// 创建临时文件
			tempFile = FileUtils.createTmpFile(this, imageConfig.getFilePath());
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
			startActivityForResult(cameraIntent, REQUEST_CAMERA);
		} else {
			Toast.makeText(this, R.string.msg_no_camera, Toast.LENGTH_SHORT).show();
		}
	}

}